import Vue from 'vue'
import $ from 'jquery'
import { onReady } from '@/utils/dom'
import Logger from '@/services/logger-service'
import '@/styles/notice.less'

const isServer = Vue.prototype.$isServer

const logger = new Logger('alert-service')

const DEFAULT_EXISTS_TIME = 3 * 1000

let counter = 0

const NoticeComponent = Vue.extend({
  template:
    '<transition-group name="notice" tag="div" class="notice-container">\n' +
    '        <div v-bind:key="notice.id" v-for="notice in notices" class="notice" :class="notice.type"\n' +
    '             @click="notice.onClick">\n' +
    '          {{notice.msg}}\n' +
    '        </div>\n' +
    '      </transition-group>',
  data () {
    return {
      notices: []
    }
  },
  methods: {
    addNotice (msg: string, type: 'info' | 'warn', time?: number) {
      const id = counter++
      const exists = time * 1000 || DEFAULT_EXISTS_TIME
      const onRemove = () => {
        const index = this.notices.findIndex(n => n.id === id)
        if (index >= 0) {
          this.notices.splice(index, 1)
        }
      }
      this.notices.push({
        id: id,
        msg: msg,
        type: type,
        onClick: onRemove
      })
      if (exists > 0) {
        setTimeout(onRemove, exists)
      }
    }
  }
})

const notice = new NoticeComponent()

if (!isServer) {
  let noticeDiv = document.getElementById('notice')
  if (noticeDiv) {
    notice.$mount(noticeDiv)
    logger.debug('notice mounted.')
  }
}

export function warn (msg: string, time?: number): void {
  if (isServer) {
    return
  }
  notice.addNotice(msg, 'warn', time)
}

export function info (msg, time) {
  if (isServer) {
    return
  }
  notice.addNotice(msg, 'info', time)
}
